package utils

import "sync"

type SafeMap struct {
	lock     *sync.RWMutex
	innerMap map[interface{}]interface{}
}

func NewSafeMap() *SafeMap {
	rval := &SafeMap{
		lock: new(sync.RWMutex),
	}
	return rval
}

func (this *SafeMap) ReplaceInnerMap(newMap map[interface{}]interface{}) {
	this.lock.Lock()
	this.innerMap = newMap
	this.lock.Unlock()
}

func (this *SafeMap) Get(key interface{}, def interface{}) (rval interface{}) {
	rval = def
	this.lock.RLock()
	if this.innerMap != nil {
		v, ok := this.innerMap[key]
		if ok {
			rval = v
		}
	}
	this.lock.RUnlock()
	return
}

func (this *SafeMap) Set(key interface{}, val interface{}) {
	this.lock.Lock()
	if this.innerMap == nil {
		this.innerMap = make(map[interface{}]interface{})
	}
	this.innerMap[key] = val
	this.lock.Unlock()
}

func (this *SafeMap) Remove(key interface{}) {
	this.lock.Lock()
	if this.innerMap != nil {
		delete(this.innerMap, key)
	}
	this.lock.Unlock()
}
